package com.study.example.study.extension.easyexcel.write;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.converters.ReadConverterContext;
import com.alibaba.excel.converters.WriteConverterContext;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.data.WriteCellData;
import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * 性别转换
 *
 * @author RenYuLiang
 */
public class EasyExcelWriteGenderConverter implements Converter<Integer> {

    @Override
    public Class<?> supportJavaTypeKey() {
        // 对象属性类型
        return Integer.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        // CellData 属性类型
        return CellDataTypeEnum.STRING;
    }

    /**
     * 这里是读的时候会调用
     *
     * @param context ReadConverterContext
     * @return Integer
     */
    @Override
    public Integer convertToJavaData(ReadConverterContext<?> context) {
        // CellData 转对象属性
        String readCellValue = context.getReadCellData().getStringValue();
        if (StringUtils.isBlank(readCellValue)) {
            return null;
        }
        Integer gende = null;
        Map<Integer, String> map = this.getGender();
        for (Map.Entry<Integer, String> entry : map.entrySet()) {
            if (readCellValue.equals(entry.getValue())) {
                gende = entry.getKey();
            }
        }
        return gende;
    }

    /**
     * 这里是写的时候会调用
     *
     * @param context WriteConverterContext
     */
    @Override
    public WriteCellData<?> convertToExcelData(WriteConverterContext<Integer> context) {
        // 对象属性转 CellData
        Integer cellValue = context.getValue();
        String cellValueStr = "异常";
        if (Objects.nonNull(cellValue)) {
            String value = this.getGender().get(cellValue);
            if (StringUtils.isNotBlank(value)) {
                cellValueStr = value;
            }
        }
        return new WriteCellData<>(cellValueStr);
    }

    /**
     * 获取性别
     *
     * @return Map<Integer, String>
     */
    private Map<Integer, String> getGender() {
        Map<Integer, String> map = new HashMap<>(16);
        map.put(1, "男");
        map.put(2, "女");
        return map;
    }

}
